<template>
  <div>
    <h1>{{ name }}---{{ age }}</h1>
    <button @click="changeData">changeData</button>
  </div>
</template>

<script>
import { ref, watchEffect } from 'vue';

export default {
  setup() {
    let name = ref('code');
    let age = ref(18);

    // watchEffect 默认先执行一次
    // onInvalidate 用于清除函数的副作用
    const stop = watchEffect((onInvalidate) => {
      let timer = setTimeout(() => {
        console.log('开启定时器');
      }, 1000);

      onInvalidate(() => {
        console.log('清除定时器');
        clearTimeout(timer);
      });
      console.log(name.value);
      console.log(age.value);
    });

    const changeData = () => {
      name.value = 'fly';
      age.value++;
      // 到达临界点不继续监听数据
      if (age.value === 20) stop();
    };

    return {
      name,
      age,
      changeData,
    };
  },
};
</script>

<style lang="scss" scoped></style>
